﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using Aluetjen.EmailService.Domain.Models.Message;

namespace Aluetjen.EmailService.Domain.Models.Pipeline
{
    public class Transformation : Entity
    {
        public virtual int Id { get; set; }

        public virtual Condition Condition { get; set; }

        public virtual MessageField Field { get; set; }
        public virtual string MatchRegex { get; set; }
        public virtual string ReplacementRegex { get; set; }

        public virtual void TransformMessage(MailMessage message)
        {
            if (Condition == null || Condition.IsSatisfiedFor(message))
            {
                ApplyRegex(message);
            }
        }

        private void ApplyRegex(MailMessage message)
        {
            switch (Field)
            {
                case MessageField.Body:
                    message.Body = ApplyRegex(message.Body);
                    break;
                case MessageField.From:
                    message.From.Address = ApplyRegex(message.From.Address);
                    break;
                case MessageField.Subject:
                    message.Subject = ApplyRegex(message.Subject);
                    break;
                case MessageField.To:
                    message.To = message.To.
                        Select(t => new { Address = t.Address = ApplyRegex(t.Address), t.DisplayName }).Distinct().
                        Select(t => new MailAddress { Address = t.Address, DisplayName = t.DisplayName }).ToList();
                    break;
                default:
                    throw new InvalidOperationException("Unknown field.");
            }
        }

        private string ApplyRegex(string value)
        {
            return Regex.Replace(value, MatchRegex, ReplacementRegex);
        }
    }
}